package com.qiuyuliantu.base.service.impl;

import java.io.IOException;
import java.net.URL;
import java.security.Security;
import java.util.*;
import java.util.stream.Collectors;

import com.qiuyuliantu.common.constant.Constants;
import com.qiuyuliantu.common.core.domain.entity.SysUserMail;
import com.qiuyuliantu.common.mail.MailUtils;
import com.qiuyuliantu.common.utils.DateUtils;
import com.qiuyuliantu.common.utils.SecurityUtils;
import com.qiuyuliantu.common.utils.StringUtils;
import com.qiuyuliantu.common.utils.sign.Md5Utils;
import com.qiuyuliantu.system.service.ISysUserMailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qiuyuliantu.base.mapper.QiuAnniversaryRemindersMapper;
import com.qiuyuliantu.base.domain.QiuAnniversaryReminders;
import com.qiuyuliantu.base.service.IQiuAnniversaryRemindersService;
import sun.net.www.protocol.http.HttpURLConnection;

import javax.net.ssl.HttpsURLConnection;

/**
 * 纪念日提醒Service业务层处理
 *
 * @author 卷卷
 * @date 2024-11-19
 */
@Service
public class QiuAnniversaryRemindersServiceImpl implements IQiuAnniversaryRemindersService
{
    private static final Logger log = LoggerFactory.getLogger(Md5Utils.class);
    @Autowired
    private QiuAnniversaryRemindersMapper qiuAnniversaryRemindersMapper;

    @Autowired
    private ISysUserMailService sysUserMailService;


    /**
     * 查询纪念日提醒
     *
     * @param id 纪念日提醒主键
     * @return 纪念日提醒
     */
    @Override
    public QiuAnniversaryReminders selectQiuAnniversaryRemindersById(Long id)
    {
        return qiuAnniversaryRemindersMapper.selectQiuAnniversaryRemindersById(id);
    }

    /**
     * 查询纪念日提醒列表
     *
     * @param qiuAnniversaryReminders 纪念日提醒
     * @return 纪念日提醒
     */
    @Override
    public List<QiuAnniversaryReminders> selectQiuAnniversaryRemindersList(QiuAnniversaryReminders qiuAnniversaryReminders)
    {
        return qiuAnniversaryRemindersMapper.selectQiuAnniversaryRemindersList(qiuAnniversaryReminders);
    }

    /**
     * 新增纪念日提醒
     *
     * @param qiuAnniversaryReminders 纪念日提醒
     * @return 结果
     */
    @Override
    public int insertQiuAnniversaryReminders(QiuAnniversaryReminders qiuAnniversaryReminders)
    {
        qiuAnniversaryReminders.setCreateTime(DateUtils.getNowDate());
        qiuAnniversaryReminders.setUpdateTime(DateUtils.getNowDate());
        qiuAnniversaryReminders.setCreateBy(String.valueOf(SecurityUtils.getUserId()));
        return qiuAnniversaryRemindersMapper.insertQiuAnniversaryReminders(qiuAnniversaryReminders);
    }

    /**
     * 修改纪念日提醒
     *
     * @param qiuAnniversaryReminders 纪念日提醒
     * @return 结果
     */
    @Override
    public int updateQiuAnniversaryReminders(QiuAnniversaryReminders qiuAnniversaryReminders)
    {
        qiuAnniversaryReminders.setUpdateTime(DateUtils.getNowDate());
        qiuAnniversaryReminders.setUpdateBy(String.valueOf(SecurityUtils.getUserId()));
        return qiuAnniversaryRemindersMapper.updateQiuAnniversaryReminders(qiuAnniversaryReminders);
    }

    /**
     * 批量删除纪念日提醒
     *
     * @param ids 需要删除的纪念日提醒主键
     * @return 结果
     */
    @Override
    public int deleteQiuAnniversaryRemindersByIds(Long[] ids)
    {
        return qiuAnniversaryRemindersMapper.deleteQiuAnniversaryRemindersByIds(ids);
    }

    /**
     * 删除纪念日提醒信息
     *
     * @param id 纪念日提醒主键
     * @return 结果
     */
    @Override
    public int deleteQiuAnniversaryRemindersById(Long id)
    {
        return qiuAnniversaryRemindersMapper.deleteQiuAnniversaryRemindersById(id);
    }

    /**
     * 定时器 （ryTask.autoRemindersByMail） 执行邮箱特定提醒纪念日 特殊意义的天数，如：99，520，999，1314
     *
     */
    @Override
    public void autoRemindersByMail() {
        // 查所有状态正常的纪念日
        QiuAnniversaryReminders qiuReminder = new QiuAnniversaryReminders();
        qiuReminder.setStatus(Constants.SUCCESS);
        // 查询类型是新历的纪念日
        List<QiuAnniversaryReminders> qiuAnniversaryRemindersList = qiuAnniversaryRemindersMapper.selectQiuAnniversaryRemindersList(qiuReminder);
        // 遍历所以纪念日记录
        qiuAnniversaryRemindersList.forEach(reminder -> {

            // 执行新历提醒
            if(reminder.getReminderDateType().equals(Constants.SUCCESS)){
                autoRemindersByMailToNew(reminder);
            }
            // 执行旧历提醒
            else if(reminder.getReminderDateType().equals(Constants.FAIL)) {

                autoRemindersByMailToOld(reminder);
            }
            // 新历农历都提醒
            else {
                autoRemindersByMailToNew(reminder);
                autoRemindersByMailToOld(reminder);

            }

        });
    }

    /**
     * @Remark: * @Param 检测工作网址是否正常访问
     * @Date: 2025/2/13
     * @Authbor: lmx
     */
    @Override
    public void checkWenByMail() {
        List< Map<String, String>> urlList = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        Map<String, String> map1 = new HashMap<>();
        map.put("url", "https://zhsj.zs.gov.cn/zscq-yw");
        map.put("title", "中山市市场监督管理局知识产权促进与保护平台");
        urlList.add(map);

        map1.put("url", "https://zhsj.zs.gov.cn/zscq-ent/");
        map1.put("title", "中山市市场监督管理局知识产权一体化系统");
        urlList.add(map1);
        // 发送的服务器信息
        SysUserMail mails = new SysUserMail();
        mails.setStatus(Constants.SUCCESS);
        mails.setType("qq");
        SysUserMail sysUserMail = sysUserMailService.selectSysUserMailById(5L);

        for (Map<String, String> m: urlList) {
            if(checkURL(m.get("url"))){ // 如果
                System.out.println("网站："+m.get("title")+" 访问成功");
            }else {
                System.out.println("网站："+m.get("title")+" 访问失败");
                // 发送邮件提醒
                try {
                    // 收件人邮箱
                    List<String> receiveMails = new ArrayList<>();
                    receiveMails.add("599793832@qq.com");
                    MailUtils.sendMail(sysUserMail, receiveMails, sysUserMail.getName()+"通知：网站："+m.get("title")+" 访问失败", "网站："+m.get("title")+" 访问失败");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }



    }

    // 检测URL是否可以正常访问
    public static boolean checkURL(String urlString) {
        try {
            URL url = new URL(urlString);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000); // 设置连接超时时间
            connection.setReadTimeout(5000); // 设置读取超时时间
            int responseCode = connection.getResponseCode();
            return responseCode == HttpURLConnection.HTTP_OK; // 如果返回码为200，表示访问成功
        } catch (IOException e) {
            e.printStackTrace();
            return false; // 如果发生异常，表示访问失败
        }
    }

    /**
     *
     * @author 一叶知秋
     * @description 执行新历纪念日提醒
     * @date 2024/12/11 16:07
     */
    public void autoRemindersByMailToNew(QiuAnniversaryReminders reminder){
        if(StringUtils.isNotEmpty(reminder.getSpecialDay())){
            // 获取要提醒的特定天数 如：99，520，999，1314
            String[] daysList = reminder.getSpecialDay().split(";");

            // 获取提前几天提醒
            long beforeDay = reminder.getDays();
            // 获取当前时间和纪念日时间的天数差
            long timeDistanceByDay = DateUtils.timeDistanceByDay(DateUtils.getNowDate(),reminder.getDateNew());
            // 循环特定提醒天数,判断是提醒该特定的时间纪念日
            for (String day : daysList) {
                Long renderDay = Long.valueOf(day);
                // 判断过去的时间  day-beforeDay =< timeDistanceByDay =< day
                // 判断今天是否在固定特定天数提前天数内，决定是否发送邮件提醒
                if ((renderDay-beforeDay) <= timeDistanceByDay && timeDistanceByDay <= renderDay ) {
                    // 查用户正常的服务器邮箱
                    SysUserMail mails = new SysUserMail();
                    mails.setStatus(Constants.SUCCESS);
                    mails.setUserId(Long.valueOf(reminder.getCreateBy()));// 获取纪念日创建人的服务器邮箱
                    List<SysUserMail> sysUserMailList = sysUserMailService.selectSysUsermailist(mails);
                    // 存在多个服务器邮箱，则循环发送
                    sysUserMailList.forEach(sysUserMail -> {
                        // 邮箱标题

                        String tile = reminder.getName()+"-特殊日期提醒";
                        // 邮箱详情 可以是邮件内容，也可以是邮件模板
                        String content = "您有一个特殊日期即将到期，请及时查收喔。<br/>" +
                                "特殊日期："+ DateUtils.parseDateToStr("yyyy/MM/dd HH:mm:ss",reminder.getDateNew())+"<br/>" +
                                "距今："+ DateUtils.timeDistance(DateUtils.getNowDate(), reminder.getDateNew())+"<br/>" +
                                "距离特定天数："+ day +"<br/>纪念日还剩"+ (renderDay-timeDistanceByDay) +"天";
                        try {
                            List<String> reminderlist = Arrays.stream(reminder.getRecipient().split(","))
                                    .filter(s -> !s.isEmpty())
                                    .collect(Collectors.toList());
                            MailUtils.sendMail(sysUserMail, reminderlist, tile, content);
                        } catch (Exception e) {
                            log.error("执行发邮件提醒 <"+reminder.getName()+">纪念日提醒失败", e);
                            e.printStackTrace();
                        }
                    });
                }
            }

        }
    }

    /**
     *
     * @author 一叶知秋
     * @description 执行旧历纪念日提醒
     * @date 2024/12/11 16:07
     */
    public void autoRemindersByMailToOld(QiuAnniversaryReminders reminder){
        if(StringUtils.isNotEmpty(reminder.getSpecialDay())){
            // 获取要提醒的特定天数 如：99，520，999，1314
            String[] daysList = reminder.getSpecialDay().split(";");

            // 获取提前几天提醒
            long beforeDay = reminder.getDays();
            // 获取当前时间和纪念日时间的天数差
            long timeDistanceByDay = DateUtils.timeDistanceByDay(DateUtils.getNowDate(),reminder.getDateNew());
            // 循环特定提醒天数,判断是提醒该特定的时间纪念日
            for (String day : daysList) {
                Long renderDay = Long.valueOf(day);
                // 判断过去的时间  day-beforeDay =< timeDistanceByDay =< day
                // 判断今天是否在固定特定天数提前天数内，决定是否发送邮件提醒
                if ((renderDay-beforeDay) <= timeDistanceByDay && timeDistanceByDay <= renderDay ) {
                    // 查用户正常的服务器邮箱
                    SysUserMail mails = new SysUserMail();
                    mails.setStatus(Constants.SUCCESS);
                    mails.setUserId(Long.valueOf(reminder.getCreateBy()));// 获取纪念日创建人的服务器邮箱
                    List<SysUserMail> sysUserMailList = sysUserMailService.selectSysUsermailist(mails);
                    // 存在多个服务器邮箱，则循环发送
                    sysUserMailList.forEach(sysUserMail -> {
                        // 邮箱标题

                        String tile = reminder.getName()+"-特殊日期提醒";
                        // 邮箱详情 可以是邮件内容，也可以是邮件模板
                        String content = "您有一个特殊日期即将到期，请及时查收喔。<br/>" +
                                "特殊日期："+ DateUtils.parseDateToStr("yyyy/MM/dd HH:mm:ss",reminder.getDateNew())+"<br/>" +
                                "距今："+ DateUtils.timeDistance(DateUtils.getNowDate(), reminder.getDateNew())+"<br/>" +
                                "距离特定天数："+ day +"<br/>纪念日还剩"+ (renderDay-timeDistanceByDay) +"天";
                        try {
                            List<String> reminderlist = Arrays.stream(reminder.getRecipient().split(","))
                                    .filter(s -> !s.isEmpty())
                                    .collect(Collectors.toList());
                            MailUtils.sendMail(sysUserMail, reminderlist, tile, content);
                        } catch (Exception e) {
                            log.error("执行发邮件提醒 <"+reminder.getName()+">纪念日提醒失败", e);
                            e.printStackTrace();
                        }
                    });
                }
            }

        }
    }
}
